/**
 * Created by zlj on 2016/12/8.
 */
var $ = require('jquery');
require('easyui');
require('layout/uiJs');
require('js-path/jquery-validation-wrapper');
var $alert = require("libs/alert");
var $confirm = require("libs/confirm");
var tradeStatus = {"processing":"待审核","closed":"审核通过","failed":"审核失败"};
var validator = null;
var isSale = require('libs/user-type').isSale;
$(function () {
    $.parser.parse();
    $('#goodsdetail').on('hidden.bs.modal',function () {
        $('#factPayerName').val('');
        $('#factAmount').val('');
        $('#factTransDt').val('').data('utc0','');
        $('#processRemark').val('');
        validator.resetForm();
    });
    $('.mydate')
        .on('changeDate', function(ev){
            validator.element("#factTransDt");
        });

    //列表审核按钮
    $('body').on('click','a[name=audi]',function () {
        var rowsData =  $('#check_table').datagrid('getRows');
        var id = rowsData[$(this).attr('row')].id;
        loadDetail(id);
    });
    validator = $('#check-sumbit').validateWapper({
        rules: {
            factAmount:{
                required:function (element) {
                    return $('#check-sumbit input[name=operateType]:checked').val() === 'closed';
                },
                number:true
            },
            factTransDt:{
                required:function (element) {
                    return $('#check-sumbit input[name=operateType]:checked').val() === 'closed';
                }
            },
            processRemark:{
                required:function (element) {
                    return $('#check-sumbit input[name=operateType]:checked').val() === 'failed';
                }
            }
        },
        messages: {
            factAmount:{required:'实际支付金额必填',number:'数字格式'},
            factTransDt:{required:'实际收款时间必填'},
            processRemark:{required:'备注必填'}
        },
        submitHandler: function() {
            var formData = $('#check-sumbit').serializeObject();
            formData.factTransDt = $('#factTransDt').data('utc0');
            $.ajax({
                url: 'api/v1/p/crm/recharge/operate',
                type: 'post',
                data: JSON.stringify(formData),
                contentType: 'application/json;charset=utf-8'
            })
                .done(function (res) {
                    if(res.code =='200'){
                        $("#goodsdetail").modal("hide");
                        $("#check_table").datagrid("reload");
                    }else{
                        $alert(res.message);
                    }
                });
        }
    });
    $("#check-sumbit input[name=operateType]").on("change",function () {
        validator.form();
        if(this.value =='closed'){
            $('#areatext').hide();
        }else{
            $('#areatext').show();
        }
    });
    tbaleinit();
    receiptAccountInit();
    $('#tb a[name=search]').on('click',function () {
        var d1 = $('#startDt').datebox('getValue');
        var d2 = $('#endDt').datebox('getValue');
        $('#check_table').datagrid('load',{
            receiptAccountId:$('#tb input[name=receiptAccountId]').val(),
            starDate:d1?$('#startDt').data('utc0'):'',
            endDate:d2?$('#endDt').data('utc0'):'',
            tradeStatus:$('#tb input[name=tradeStatus]').val(),
            originSystem:'MMS'
        })
    });

    //审核提交按钮
    $('#checkSubmit').on('click',function (e) {
        e.preventDefault();
        $("#check-sumbit").submit();
    });
});

function tbaleinit() {
    $('#check_table').datagrid({
        url:'api/v1/p/crm/recharge/list',
        border : false,
        height:$(window).height(),
        pagination : true,
        idField : 'id',
        pageSize : 20,
        pageList : [ 20, 50,  100 ],
        checkOnSelect : false,//单击选中
        emptyMsg : "暂无数据",
        selectOnCheck : true,
        rownumbers:true,
        queryParams: {
            originSystem:'MMS'
        },
        /*frozenColumns:[[{
            field : 'id',
            checkbox:true
        }]],*/
        columns:[[{
                field:'accountName',
                title:'企业名称'
            },{
                field:'transDt',
                title:'汇款时间'
            },{
                field:'receiptAccountName',
                title:'收款账号名称'
            },{
                field:'currency',
                title:'币种'
            },{
                field:'amount',
                title:'汇款金额'
            },{
                field:'payerName',
                title:'付款人姓名'
            },{
            field:'factAmount',
            title:'实际支付金额'
        },{
            field:'factTransDt',
            title:'实际收款时间',
            formatter:function (value,row,index) {
                if(value !='') {
                    return new Date(value.replace(/-/g, "/")).format("yyyy-MM-dd");
                }else{
                    return '';
                }
            }
        },{
                field:'processStatus',
                title:'审核状态',
                formatter:function (value,row,index) {
                    return tradeStatus[value];
                }
            },{
                field:'opt',
                title:'操作',
                hidden:isSale,
                formatter:function (value,row,index) {
                    switch (row.processStatus){
                        case 'processing':
                            return '<a href="javascript:;" name="audi" row="'+index+'"><i class="glyphicon glyphicon-pencil"></i>审核</a>';
                        default :return "";
                    }
                }
            }
        ]],
        loadFilter:function(data){
            if(data.code!='200'){
                $alert(data.message);
                return data.data;
            }
            return data.data;
        },
        onClickRow:function (index,data) {
            var $row = $("#datagrid-row-r1-1-"+index).find("input[type=checkbox]");
            if(!$row.prop("checked")){
                $(this).datagrid('unselectRow', index);
            }else{
                $(this).datagrid('selectRow', index);
            }
        },
        toolbar:"#tb",
    });
    $("#ft").show();
}
//opt 操作 callback回调函数
function opt(url,data,callback) {
    $.ajax({
        url:url,
        type:'post',
        contentType: "application/json; charset=utf-8",
        data:JSON.stringify(data),
        dataType:'json',
        success:function (result) {
            callback(result);
        },
        error:function (e) {
            console.error('接口：'+url+'获取失败');
        }
    })
}
//load goods
function loadDetail(id) {
    $.ajax({
        url:'api/v1/p/crm/recharge/detail',
        type:'post',
        data:{
            id:id
        },
        dataType:'json',
        success:function (result) {
            if(result.code == 200){
                appendData(result.data);
                $('#goodsdetail').modal('show');
            }else{
                $alert(result.message);
            }
        },
        error:function (e) {
            console.error('url: api/v1/p/crm/recharge/detail 接口失败');
        }
    })
}
//append data
function appendData(data) {
    $('#myModalLabel').html(data.accountName);
    $('#id').val(data.id);
    var $spans = $('#goodsdetail div.iteam span');
    $($spans[0]).html(data.transDt);
    $($spans[1]).html(data.receiptAccountName);
    $($spans[2]).html(data.currency);
    $($spans[3]).html(data.amount);
    $($spans[4]).html(data.payerName);
    var $attachments = $('#attachments');
    $('#attachments').empty();
    $.each(data.attachments,function (i,o) {
        $attachments.append('<a href="'+o.filePath+'" target="_blank" name="fileName">'+o.fileRealName+'</a><br>');
    });
    // $attachments.on('click','a[name=fileName]',function () {
    //     window.open(data.attachments[0].filePath);
    //     /*window.open("api/v1/p/crm/fileoper/download?id="+data.attachments[0].id);*/
    // });
    $($spans[6]).html(data.remark);
    if(data.processStatus == 'failed'){
        $("input[name='operateType']").get(1).checked=true;
    }else {
        $("input[name='operateType']").get(0).checked=true;
        $('#areatext').hide();
    }
}

//ajax操作通用 url 地址 data 数据
function optfun(url,data) {
    if(data.operateType == 'failed' && data.processRemark == ''){
        $alert('审核失败原因不能为空!');
        return;
    }
    if(data.operateType == 'failed' && data.processRemark == ''){
        $alert('审核失败原因不能为空!');
        return;
    }
    if( data.operateType == 'closed' && data.factAmount == ''){
        $alert('实际支付金额不能为空!');
        return;
    }
    $.ajax({
        url:url,
        type:'post',
        contentType: "application/json; charset=utf-8",
        data:JSON.stringify(data),
        dataType:'json',
        success:function (result) {
            if(result.code =='200'){
                $("#goodsdetail").modal("hide");
                $("#check_table").datagrid("reload");
            }else{
                $alert(result.message);
            }
        },
        error:function (e) {
            $alert("操作失败，请联系管理员")
        }
    });
}

function receiptAccountInit() {
    $("#receiptAccountId").combobox({
        url:'api/v1/p/crm/receiptAccount/list',
        valueField:'receiptAccountId',
        textField:'accountName',
        queryParams:{},
        loadFilter:function(result){
            if(result.code=='200'){
                result.data.rows.unshift({receiptAccountId:'',accountName:'全部'});
                return result.data.rows;
            }
        }
    })
}